﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

using NFL.DataAccess;

namespace NFL.Business
{
    public class Business
    {
        // Private variables
        private NFL.Business.LiveScores ls;
        private NFL.DataAccess.DataAccess da;

        public Business()
        {
            ls = new LiveScores();
            da = new DataAccess.DataAccess();
        }


        public int GetWeekID(DateTime currentDate)
        {
            return da.GetWeekID(currentDate);
        }


        public bool? IsTeamWinner(string teamShortName, int weekID)
        {
            return ls.IsTeamWinner(teamShortName, weekID);
        }

        public int GetTeamID(string teamName)
        {
            return da.GetTeamID(teamName);
        }

        public IList<int> GetWinners()
        {
            return ls.GetCompletedScores().ToList();
        }

        public IList<WinnersLosers> GetWinnersAndLosers(int weekID)
        {
            return ls.GetWinnersLosers(weekID);
        }

        public DataTable GetScores(int weekID, int division)
        {
            try
            {
                // Get the current live scores
                ls.GetLiveScores();

                // Data table to hold data as its build
                DataTable pickTable = new DataTable();

                // Build initial grid of games based on the week
                pickTable = ls.BuildWeekGrid();

                // Fill in grid with users and their picks
                pickTable = ls.FillWeekGrid(division, pickTable);

                // Update the table with win and loss data
                pickTable = ls.UpdateGridWinLossesWithScores(pickTable);

                //var dt = ls.BuildWeekGrid();
                //var dt2 = ls.FillWeekGrid(dt);
                //var dt3 = ls.UpdateGridWinLossesWithScores(dt2);

                // Determinie winner and check tie breaker if needed
                pickTable = ls.DetermineWinner(pickTable);
                
                // Sort datatable based on wins and user id
                System.Data.DataTable finalTable;
                System.Data.DataView dv = pickTable.DefaultView;
                dv.Sort = "wins desc, userid asc";
                finalTable = dv.ToTable();

                // Get the table header row
                DataTable  hdrRow = ls.GetHeaderGamesRow();

                // Merge table header to top of picks table

                pickTable = ls.MergeHeaderAndData(hdrRow, finalTable);


                return pickTable;

            }
            catch 
            {
                return null;
            }
        
        }


    }
}
